<?php

namespace App\Http\Controllers;

use App\EcmsHtfComment;
use App\EcmsNew;
use App\EcmsNewClass;
use App\Http\Extend\Helper;
use App\UserWechat;
use Curl\Curl;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class IndexController extends Controller
{
    protected $file_api = ['n.id','n.titleurl','n.title','n.titlepic','n.smalltext','c.classname','n.classid'];
    protected $tuofa = [19,21,22,74,23,24,25,26,27,28,66,69,70,72,60,61,62,63,64,65,101,102,103,104,105,107,73,12,33,67,68,88,89,90,91,92,93,96,97,98,99,112,113,114,115,122,123,124,125];
    public $show_sw = 1; //默认显示商务通

    /**
     * 数据获取
     * @param $classArray
     * @param string $page
     * @param string $rows
     * @param string $isGood
     * @return mixed
     * create by wenQing
     */
    public function getData($classArray,$page = '',$rows = '4',$isGood = '')
    {
        $rows = $rows ? $rows : 5;
        $page = $page ? $page : 0;
        $start = ($page-1)*$rows;

        $temp = DB::table('phome_ecms_news as n')->leftJoin('phome_enewsclass as c','n.classid','=','c.classid')
            ->select($this->file_api)->orderBy('n.id','desc')->offset($start)->limit($rows);
        if(is_array($classArray))
        {
            $temp = $temp->whereIn('n.classid',$classArray);
        }
        else
        {
            $temp = $temp->where('n.classid',$classArray);
        }
        if($isGood) $temp = $temp->where('n.isgood','=',$isGood);

        if($rows == '1')
        {
            $data = $temp->first();
        }
        else
        {
            $data = $temp->get();
        }

        //修正一下图片链接显示不正确的问题
        foreach ($data as $k => $v)
        {
            if(!empty($v->titlepic) && !preg_match('/www./',$v->titlepic) && is_array($v->titlepic))
            {
                $data->$k->titlepic = 'http://www.haotoufa.com'.$v->titlepic;
            }
            elseif (is_string($v) && $k == 'titlepic')
            {
                if(!preg_match('/www./',$v)) $data['titlepic'] = 'http://www.haotoufa.com'.$v;
            }
        }

        return $data;
    }

    /**
     * 首页视图
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function index()
    {
        //判断是否跳转到pc站
        if(Helper::checkPc())
        {
            header("Location:".'http://www.haotoufa.com/');
            dd('error');
        }

        $banner = EcmsNew::where('isgood',9)->orderBy('id', 'desc')->limit(5)->get(['id','titleurl','title','titlepic']);

        return view('index',[
            'config' => config('haotoufa'),
            'menu' => config('menu'),
            'menu_click' => config('menu_click'),
            'banner' => $banner,
            'hotData' => $this->getData([141,142,143],1,3,''),
            'yangFaData' => [
                'banner' => $this->getData([29,31,32,126],'',1,1),
                'data' => $this->getData([29,31,32,126],1,4)
            ],
            'tuoFaData' => [
                'banner' => $this->getData($this->tuofa,'',1,1),
                'data' => $this->getData($this->tuofa,1,4)
            ],
            'zhiFaData' => [
                'banner' => $this->getData([276,277,278,279,280,281,282,283,284,285],'',1,1),
                'data' => $this->getData([276,277,278,279,280,281,282,283,284,285],1,4)
            ],
            'faXingData' => [
                'banner' => $this->getData([168,169,170,171,172,173,174,175,176,177,270],'',1,1),
                'data' => $this->getData([168,169,170,171,172,173,174,175,176,177,270],1,4)
            ],
            'show_sw' => $this->show_sw
        ]);
    }

    /**
     * 文章栏目页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function article_list(Request $request)
    {
        $class = $request->classid;
        //判断一下类别下是否有子目录
        $newsClass = EcmsNewClass::where('classid',$request->classid)->get(['classid','sonclass','classname','classpagekey','bclassid','bname','intro','classpath','classurl'])->toArray();
        $parentClass = EcmsNewClass::where('classid',$newsClass[0]['bclassid'])->get(['classid','classname'])->toArray();

        //判断是否跳转到pc站
        if(Helper::checkPc())
        {
            if($newsClass[0]['classurl'])
            {
                header("Location:".$newsClass[0]['classurl']);
            }
            else
            {
                header("Location:".'http://www.haotoufa.com/'.$newsClass[0]['classpath']);
            }
            dd('error');
        }

        //判断是否显示商务通
        if($newsClass[0]['classid'] == '5' || $newsClass[0]['classid'] == '144') $this->show_sw = 0;
        if($parentClass)
            if($parentClass[0]['classid'] == '5' || $parentClass[0]['classid'] == '144') $this->show_sw = 0;

        $bread = ''; //保存面包屑
        if($newsClass[0]['sonclass'])
        {
            $class = explode('|',$newsClass[0]['sonclass']);
            foreach($class as $k => $v)
            {
                if(empty($v)) unset($class[$k]);
            }
        }
        if($parentClass)
        {
            $bread = '<span> > </span><span> <a href="'.url('article_list/'.$newsClass[0]['bclassid']).'">'.$parentClass[0]['classname'].'</a> </span>';
            $bread .= '<span> > </span><span> <a hre="'.url('article_list/'.$request->classid).'">'.$newsClass[0]['classname'].'</a></span>';
        }
        else
        {
            $bread .= '<span> > </span><span> <a hre="'.url('article_list/'.$request->classid).'">'.$newsClass[0]['classname'].'</a></span>';
        }

        return view('article_list',[
            'keywords' => $newsClass[0]['classpagekey'],
            'description' => $newsClass[0]['intro'],
            'title' => $newsClass[0]['bname'],
            'menu' => config('menu'),
            'menu_click' => config('menu_click'),
            'data' => $this->getData($class,$request->page,8),
            'class_name' => $newsClass[0]['classname'],
            'parent_class_name' => $parentClass ? $parentClass[0]['classname'] : '',
            'class_id' => $request->classid,
            'bread' => $bread,
            'show_sw' => $this->show_sw
        ]);
    }

    public function search(Request $request)
    {
        $str = $request->query('str');
        $class_id = $request->query('class_id');
        $data = DB::table('phome_ecms_news as n')->leftJoin('phome_enewsclass as c','n.classid','=','c.classid')
            ->select($this->file_api)->where('n.title','like','%'.$str.'%')->where('n.classid',$class_id)->orderBy('n.id','desc')->get()->toArray();

        return view('search',[
            'show_sw' => 0,
            'keywords' => $str,
            'data' => $data,
            'menu' => config('menu'),
            'menu_click' => config('menu_click'),
            'bread' => ''
        ]);
    }

    /**
     * 页面跳转
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function redirect_article(Request $request)
    {
        $article = EcmsNew::findOrFail($request->id);
        return redirect('article/'.$article->id);
    }
    /**
     * 文章详情页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function article(Request $request)
    {
        $article = EcmsNew::findOrFail($request->id);
        if(Helper::checkPc())
        {
            header("Location:".$article->titleurl);
            dd('error');
        }
        //修改一下图片的链接显示
        $data = str_replace("src=\"/", "src=\"http://www.haotoufa.com/", stripslashes($article->newstext));
        $article->newstext = str_replace("href=\"/", "src=\"http://www.haotoufa.com/", $data);

        //获取一下页面的关键字
        $keyArr = [];
        if($article->keyboard)
        {
            $key = $article->keyboard;
            //显示一下详情页标签
            $keyArr = explode(',',$key);
        }
        else
        {
            //获取父类的关键字，作为页面的关键字
            $class = EcmsNewClass::find($article->classid);
            $key = $class->classpagekey;
        }

        //相关阅读
        $abouts = EcmsNew::where('classid',$article->classid)->where('titlepic','!=','')->orderBy('onclick', 'desc')->limit(4)->get(['id','titleurl','title','titlepic','classid']);
        //最新推荐
        $news = EcmsNew::where('classid',$article->classid)->orderBy('id', 'desc')->limit(5)->get(['id','titleurl','title','titlepic','classid']);
        $class = EcmsNewClass::where('classid',$article->classid)->first();

        $abouts = $this->changePicUrl($abouts);
        $news = $this->changePicUrl($news);
        $bread = '';

        if($class->bclassid == '5' || $class->bclassid == '144') $this->show_sw = 0;  //是否显示商务通
        if($class->bclassid)
        {
            $parent = EcmsNewClass::where('classid',$class->bclassid)->first();
            if($parent)
                if($parent->bclassid == '5' || $parent->bclassid == '144') $this->show_sw = 0; //是否显示商务通

            $bread .= '<span> > </span><span> <a href="'.url('article_list/'.$parent->classid).'">'.$parent->classname.'</a></span>';
            $bread .= '<span> > </span><span> <a href="'.url('article_list/'.$article->classid).'">'.$class->classname.'</a></span>';
        }
        else
        {
            $bread .= '<span> > </span><span> <a href="'.url('article_list/'.$article->classid).'">'.$class->classname.'</a></span>';
        }

        //显示评论信息
        $commentCount = EcmsHtfComment::where('a_id',$request->id)->where('sh',1)->count();
        $commentList = EcmsHtfComment::where('a_id',$request->id)->where('sh',1)->where('p_id',1)->orderBy('zan','DESC')->limit(3)->get()->toArray();

        return view('article',[
            'data' => $article,
            'keywords' => $key,
            'abouts' => $abouts,
            'news' => $news,
            'class_name' => $class->classname,
            'class_id' => $request->id,
            'parent_id' => $class->classid,
            'bread' => $bread,
            'comment' => [
                'comment_count' => $commentCount,
                'comment_list' => $commentList
            ],
            'show_sw' => $this->show_sw,
            'keyArr' => $keyArr
        ]);
    }

    /**
     * 处理一下图片的路径
     * @param $arr
     * @return mixed
     * create by wenQing
     */
    public function changePicUrl($arr)
    {
        foreach ($arr as $k => $v)
        {
            if(!empty($v->titlepic) && !preg_match('/haotoufa/',$v->titlepic) && is_string($v->titlepic))
            {
                $arr[$k]->titlepic = 'http://www.haotoufa.com'.$v->titlepic;
            }
            elseif (is_string($v) && $k == 'titlepic')
            {
                if(!preg_match('/www./',$v)) $data['titlepic'] = 'http://www.haotoufa.com'.$v;
            }
        }

        return $arr;
    }

    /**
     * 关于我们界面显示
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function about()
    {
        return view('about',[
            'menu' => config('menu'),
            'menu_click' => config('menu_click'),
            'show_sw' => $this->show_sw
        ]);
    }

    public function comment(Request $request)
    {
        $rows = 7; // 每页显示数目
        $start = 0;

        $eHtfComment = new EcmsHtfComment();
        //获取最热前三条
        $hotData = $eHtfComment->where('a_id',$request->id)->where('p_id',1)->where('sh',1)->orderBy('zan','DESC')->limit(3)->get()->toArray();
        $count = $eHtfComment->where('a_id',$request->id)->where('p_id',1)->where('sh',1)->count();
        $data = $eHtfComment->where('a_id',$request->id)->where('p_id',1)->where('sh',1)->whereNotIn('id',array_column($hotData,'id'))
            ->offset($start)->limit($rows)->orderBy('create_time','DESC')->get()->toArray();
        $data = array_merge($hotData,$data); //一条的时候只显示一个

        //查找评论
        $comment = $eHtfComment->where('a_id',$request->id)->where('sh',1)->whereIn('p_id',array_column($data,'id'))->get()->toArray();
        foreach ($data as $k => &$v)
        {
            $v['comment'] = [];
            if($comment)
            {
                foreach ($comment as $k2 => &$v2)
                {
                    if($v2['p_id'] == $v['id'])
                        $v['comment'][] = $v2;
                }
            }
        }

        return view('comment',[
            'data' => $data,
            'count' => $count,
            'a_id' => $request->id,
            'page' => 1
        ]);
    }

    /**
     * 评论列表加载更多
     * @param Request $request
     * @return string
     * create by wenQing
     */
    public function comment_list(Request $request)
    {
        $page = $request->page ? $request->page : 1; // 开始页数
        $rows = 10; // 每页显示数目
        $start = ($page-1)*$rows;

        $eHtfComment = new EcmsHtfComment();
        //获取最热前三条
        $hotData = $eHtfComment->where('a_id',$request->id)->where('p_id',1)->where('sh',1)->orderBy('zan','DESC')->limit(3)->get()->toArray();
        $data = $eHtfComment->where('a_id',$request->id)->where('p_id',1)->where('sh',1)->whereNotIn('a_id',array_column($hotData,'id'))
            ->offset($start)->limit($rows)->orderBy('create_time','DESC')->get()->toArray();

        //查找评论
        $comment = $eHtfComment->where('a_id',$request->id)->where('sh',1)->whereIn('p_id',array_column($data,'id'))->get()->toArray();
        foreach ($data as $k => &$v)
        {
            $v['comment'] = [];
            if($comment)
            {
                foreach ($comment as $k2 => &$v2)
                {
                    if($v2['p_id'] == $v['id'])
                        $v['comment'][] = $v2;
                }
            }
        }
        $html = '';
        foreach ($data as $k => $v)
        {
            $id = '';
            if($k == (count($data) - 1)) $id = 'id = "end"';
            $html .= '<div class="contentBox_main_member" '.$id.'>';
            $html .= '<p class="contentBox_main_member_top"><span>'.$v['tel'].'</span><span><img width="20" height="20" src="'.asset('image/praise.png').'"><span>'.$v['zan'].'</span></span><span class="contentBox_main_member_write hf hf_p_'.$v['id'].'" p_id = "'.$v['id'].'"><img width="20" height="20" src="'.asset('image/write_comment_2.png').'"><span>回复</span></span></p>';
            $html .= '<p class="contentBox_main_member_content">'.$v['content'].'</p>';
            $html .= '<p class="contentBox_main_member_bottom">'.$v['create_time'].'</p>';
            foreach ($v['comment'] as $k2 => $v2)
            {
                $html .= '<div class="contentBox_main_member contentBox_main_child_member">';
                $html .= '<p class="contentBox_main_member_top"><span>'.$v2['tel'].'</span><span class="zan_num" p_id="'.$v2['id'].'"><img width="20" height="20" src="'.asset('image/praise.png').'"><span>'.$v2['zan'].'</span></span></p>';
                $html .= '<p class="contentBox_main_member_content">'.$v2['content'].'</p>';
                $html .= '<p class="contentBox_main_member_bottom">'.$v2['create_time'].'</p>';
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        return $html;
    }

    public function comment_add(Request $request)
    {
        return view('comment_add',[
            'a_id' => $request->id,
            'p_id' => $request->p_id
        ]);
    }

    /**
     * 评论添加操作
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * create by wenQing
     * @throws \Exception
     */
    public function comment_add_op(Request $request)
    {
        if(empty($request->yzm)) throw new \Exception('验证码不存在！');
        if($request->yzm != Cache::get('empire_'.$request->tel))
        {
            flash('验证码不存在，请重新提交！');
            return redirect('comment_add/'.$request->a_id);
        }
        $ecmHtf = new EcmsHtfComment();
        //查看是否是二级评论
        $ecmHtf->p_id = $request->p_id ? $request->p_id : 1; //所在级别
        $ecmHtf->a_id = $request->a_id;
        $ecmHtf->tel = $request->tel;
        $ecmHtf->content = $request->input('content');
        $ecmHtf->create_time = date('Y-m-d H:i:s');
        $id = $ecmHtf->save();
        if($id) Cache::forget('empire_'.$request->tel); //清空一下保存的验证码

        flash('评论提交成功，审核中...');
        return redirect('comment/'.$request->a_id);
    }

    public function test2()
    {
        Helper::sendMsg(18736007158);
//        $curl = new Curl();
//        $curl->get('https://api.weixin.qq.com/sns/jscode2session?appid=wx79f9b85f76c5f5a9&secret=85d59a1ef0a30fef7e33c3fcbb441b55&js_code=003VRBxZ03Mfe12MkMxZ0zNDxZ0VRBx8&grant_type=authorization_code');
//        if ($curl->error) {
//            echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";die;
//        } else {
//            dd(json_decode($curl->response));
//        }

        echo "<img src= '".Helper::getChartPic('1','2')."'/>";
    }
}
